<template>
  <el-container class="checkout-container">
    <el-main>
      <el-card>
        <template #header>
          <h2>确认订单信息</h2>
        </template>

        <div v-if="loadingCart" class="loading-spinner">
          <el-progress :percentage="50" :indeterminate="true" />
          <p>正在加载订单信息...</p>
        </div>
        <div v-else-if="errorCart" class="error-message">
          <el-alert 
            :title="errorCart" 
            type="error" 
            show-icon 
            :closable="false" 
          />
        </div>
        <div v-else-if="!cartItems.length" class="empty-cart-message">
          <el-empty description="购物车为空，无法结算。">
            <el-button type="primary" @click="goToProducts">去购物</el-button>
          </el-empty>
        </div>
        <div v-else>
          <el-steps :active="activeStep" finish-status="success" simple style="margin-bottom: 20px;">
            <el-step title="确认商品"></el-step>
            <el-step title="填写配送信息"></el-step>
            <el-step title="完成订单"></el-step>
          </el-steps>

          <!-- 商品概要 -->
          <el-card shadow="never" style="margin-bottom: 20px;">
            <template #header>
              <h4>商品列表 ({{ cartSummary.total_unique_items || 0 }}种, 共{{ cartSummary.total_quantity || 0 }}件)</h4>
            </template>
            <el-table :data="cartItems" size="small">
              <el-table-column prop="name" label="商品名称" />
              <el-table-column prop="price" label="单价" width="100">
                <template #default="scope">¥{{ scope.row.price.toFixed(2) }}</template>
              </el-table-column>
              <el-table-column prop="quantity" label="数量" width="80" />
              <el-table-column label="小计" width="120">
                <template #default="scope">¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}</template>
              </el-table-column>
            </el-table>
            <div class="cart-total-summary">
              <strong>订单总金额: <span style="color: #ff4d4f; font-size: 1.2em;">¥{{ (cartSummary.total_amount || 0).toFixed(2) }}</span></strong>
            </div>
          </el-card>

          <!-- 收货地址 -->
          <el-card shadow="never" v-if="!loadingAddresses">
            <template #header>
              <h4>收货地址</h4>
            </template>
            <el-form ref="addressFormRef" :model="shippingForm" label-width="100px" :rules="addressRules">
              <el-radio-group v-model="addressSelectionMode" @change="handleAddressModeChange">
                <el-radio-button value="select">选择已有地址</el-radio-button>
                <el-radio-button value="new">使用新地址</el-radio-button>
              </el-radio-group>

              <div v-if="addressSelectionMode === 'select'" style="margin-top: 15px;">
                <el-select 
                  v-model="selectedAddressId" 
                  placeholder="请选择收货地址" 
                  clearable 
                  style="width: 100%;"
                  :disabled="!userAddresses.length"
                  @change="handleExistingAddressSelect"
                >
                  <el-option 
                    v-for="addr in userAddresses" 
                    :key="addr.id" 
                    :label="`${addr.recipient_name} - ${addr.province}${addr.city}${addr.street_address} (${addr.phone_number})`" 
                    :value="addr.id"
                  />
                </el-select>
                <el-empty v-if="!userAddresses.length && !loadingAddresses" description="暂无保存的收货地址，请添加新地址。"></el-empty>
              </div>

              <div v-if="addressSelectionMode === 'new'" style="margin-top: 15px;">
                <el-form-item label="收件人" prop="recipient_name">
                  <el-input v-model="shippingForm.recipient_name" placeholder="收件人姓名" />
                </el-form-item>
                <el-form-item label="联系电话" prop="phone_number">
                  <el-input v-model="shippingForm.phone_number" placeholder="手机号码" />
                </el-form-item>
                <el-form-item label="省份" prop="province">
                  <el-input v-model="shippingForm.province" placeholder="例如：广东省" />
                </el-form-item>
                <el-form-item label="城市" prop="city">
                  <el-input v-model="shippingForm.city" placeholder="例如：深圳市" />
                </el-form-item>
                <el-form-item label="区/县" prop="district">
                  <el-input v-model="shippingForm.district" placeholder="例如：南山区 (可选)" />
                </el-form-item>
                <el-form-item label="详细地址" prop="street_address">
                  <el-input v-model="shippingForm.street_address" type="textarea" placeholder="街道、楼牌号等" />
                </el-form-item>
                <el-form-item label="邮政编码" prop="postal_code">
                  <el-input v-model="shippingForm.postal_code" placeholder="邮政编码 (可选)" />
                </el-form-item>
                <el-form-item label="设为默认">
                  <el-switch v-model="saveAsDefaultAddress" />
                  <span style="font-size: 12px; color: #909399; margin-left: 10px;"> (保存新地址时可选)</span>
                </el-form-item>
              </div>

              <el-form-item label="订单备注">
                <el-input v-model="customerRemarks" type="textarea" placeholder="选填，给商家留言" />
              </el-form-item>
            </el-form>
          </el-card>
          
          <div style="text-align: center; margin-top: 30px;">
            <el-button @click="router.push({name: 'Cart'})">返回购物车</el-button>
            <el-button type="primary" size="large" @click="handleSubmitOrder" :loading="submittingOrder">
              提交订单
            </el-button>
          </div>
        </div>
      </el-card>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, onMounted, computed, reactive, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import cartService from '../api/cart.service';
import orderService from '../api/order.service';
import addressService from '../api/address.service';
import { ElMessage, ElMessageBox } from 'element-plus';

const router = useRouter();

const activeStep = ref(1); // 控制步骤条

// 购物车数据
const cartData = ref({ items: [], summary: {} });
const loadingCart = ref(true);
const errorCart = ref(null);
const cartItems = computed(() => {
  console.log('计算购物车商品列表:', cartData.value.items);
  return cartData.value.items || [];
});
const cartSummary = computed(() => {
  console.log('计算购物车汇总信息:', cartData.value.summary);
  return cartData.value.summary || {};
});

// 地址数据
const userAddresses = ref([]);
const loadingAddresses = ref(true);
const errorAddresses = ref(null);
const addressSelectionMode = ref('select'); // 'select' or 'new'
const selectedAddressId = ref(null);
const saveAsDefaultAddress = ref(false);

const addressFormRef = ref(null);
const shippingForm = reactive({
  recipient_name: '',
  phone_number: '',
  street_address: '',
  city: '',
  district: '',
  province: '',
  postal_code: '',
  country: '中国', // 默认中国
});

const addressRules = {
  recipient_name: [{ required: true, message: '请输入收件人姓名', trigger: 'blur' }],
  phone_number: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  province: [{ required: true, message: '请输入省份', trigger: 'blur' }],
  city: [{ required: true, message: '请输入城市', trigger: 'blur' }],
  street_address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
};

// 订单备注
const customerRemarks = ref('');

// 提交状态
const submittingOrder = ref(false);

const fetchCartData = async () => {
  loadingCart.value = true;
  errorCart.value = null;
  try {
    console.log('开始获取购物车数据...');
    const response = await cartService.getCart();
    console.log('获取到的购物车数据:', response);
    
    if (response && response.data) {
      // 确保数据格式正确
      const items = Array.isArray(response.data) ? response.data : [];
      const summary = response.meta || {};
      
      cartData.value = {
        items: items,
        summary: {
          total_amount: summary.total_amount || 0,
          total_quantity: summary.total_quantity || 0,
          total_unique_items: summary.total_unique_items || items.length
        }
      };
      
      console.log('处理后的购物车数据:', cartData.value);
      console.log('购物车商品数量:', cartData.value.items.length);
    } else {
      cartData.value = { items: [], summary: {} };
      console.warn('[Checkout.vue] 获取到的购物车数据结构不符合预期:', response);
    }

    if (!cartData.value.items || cartData.value.items.length === 0) {
      ElMessage.warning('购物车为空，无法结算。');
    }
  } catch (err) {
    console.error('[Checkout.vue] 加载购物车信息失败:', err);
    errorCart.value = err.message || '加载购物车信息失败';
    ElMessage.error(errorCart.value);
    cartData.value = { items: [], summary: {} };
  } finally {
    loadingCart.value = false;
    console.log('购物车数据加载完成，loadingCart:', loadingCart.value);
  }
};

const fetchUserAddresses = async () => {
  loadingAddresses.value = true;
  errorAddresses.value = null;
  try {
    console.log('开始获取用户地址...');
    const response = await addressService.getAddresses();
    console.log('获取到的地址数据:', response);
    
    userAddresses.value = response.data || [];
    
    if (userAddresses.value.length > 0) {
      const defaultAddr = userAddresses.value.find(addr => addr.is_default_shipping);
      selectedAddressId.value = defaultAddr ? defaultAddr.id : userAddresses.value[0].id;
      handleExistingAddressSelect(selectedAddressId.value);
      addressSelectionMode.value = 'select';
    } else {
      addressSelectionMode.value = 'new';
    }
  } catch (err) {
    console.error('[Checkout.vue] 加载地址信息失败:', err);
    errorAddresses.value = err.message || '加载收货地址失败';
    ElMessage.error(errorAddresses.value);
    addressSelectionMode.value = 'new';
  } finally {
    loadingAddresses.value = false;
    console.log('地址数据加载完成，loadingAddresses:', loadingAddresses.value);
  }
};

const handleAddressModeChange = (mode) => {
  if (mode === 'select' && userAddresses.value.length > 0 && selectedAddressId.value) {
     handleExistingAddressSelect(selectedAddressId.value);
  } else if (mode === 'new') {
    // 清空或重置 shippingForm, selectedAddressId
    selectedAddressId.value = null;
    Object.keys(shippingForm).forEach(key => shippingForm[key] = '');
    shippingForm.country = '中国';
  }
};

const handleExistingAddressSelect = (addressId) => {
  const addr = userAddresses.value.find(a => a.id === addressId);
  if (addr) {
    Object.assign(shippingForm, {
      recipient_name: addr.recipient_name,
      phone_number: addr.phone_number,
      street_address: addr.street_address,
      city: addr.city,
      district: addr.district || '',
      province: addr.province,
      postal_code: addr.postal_code || '',
      country: addr.country || '中国',
    });
  }
};

const handleSubmitOrder = async () => {
  activeStep.value = 2;
  let isValidAddress = false;
  let addressId = null;

  if (addressSelectionMode.value === 'select') {
    if (!selectedAddressId.value) {
      ElMessage.error('请选择一个收货地址');
      activeStep.value = 1;
      return;
    }
    addressId = selectedAddressId.value;
    isValidAddress = true;
  } else {
    // 新地址模式
    await addressFormRef.value.validate(async (valid) => {
      if (valid) {
        try {
          // 先保存新地址
          const response = await addressService.addAddress({
            ...shippingForm,
            is_default_shipping: saveAsDefaultAddress.value
          });
          addressId = response.data.id;
          isValidAddress = true;
        } catch (err) {
          console.error('保存新地址失败:', err);
          ElMessage.error(err.message || '保存新地址失败，请稍后再试');
          activeStep.value = 1;
        }
      } else {
        ElMessage.error('请检查并正确填写收货地址信息');
        activeStep.value = 1;
      }
    });
  }

  if (!isValidAddress || !addressId) return;

  // 检查购物车是否为空
  if (!cartItems.value || cartItems.value.length === 0) {
    ElMessage.error('购物车为空，无法提交订单');
    activeStep.value = 1;
    return;
  }

  submittingOrder.value = true;
  try {
    console.log('准备提交订单，购物车数据:', cartItems.value);
    let orderPayload = {
      shipping_address_id: addressId,
      customer_remarks: customerRemarks.value || null,
      items: cartItems.value.map(item => ({
        product_id: item.product_id,
        quantity: item.quantity,
        price: item.price
      }))
    };
    
    console.log('提交订单数据:', orderPayload);
    const response = await orderService.createOrder(orderPayload);
    console.log('订单创建成功:', response);
    
    activeStep.value = 3;
    ElMessage.success('订单提交成功！');
    
    // 使用 window.location.href 直接跳转
    const orderNumber = response.data.order_number;
    window.location.href = `/order-confirmation/${orderNumber}`;
  } catch (err) {
    console.error('提交订单失败:', err);
    ElMessage.error(err.message || '提交订单失败，请稍后再试');
    activeStep.value = 1;
  } finally {
    submittingOrder.value = false;
  }
};

const goToProducts = () => {
  router.push({ name: 'Products' });
};

onMounted(async () => {
  console.log('Checkout组件挂载，开始加载数据...');
  try {
    await fetchCartData();
    if (cartItems.value.length > 0) {
      await fetchUserAddresses();
    }
  } catch (err) {
    console.error('初始化数据加载失败:', err);
    ElMessage.error('加载数据失败，请刷新页面重试');
  }
  console.log('初始化数据加载完成');
});

</script>

<style scoped>
.checkout-container {
  padding: 20px;
}
.loading-spinner, .error-message, .empty-cart-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 200px;
}
.cart-total-summary {
    text-align: right;
    margin-top: 15px;
    padding-top: 15px;
    border-top: 1px solid #ebeef5;
}
</style> 